package com.shopoo.oauth.wechat.utils;

import java.io.UnsupportedEncodingException;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JwtUtil {

    private static String secret="TYUIOHJKRTYUIOFS345678RTYFGHJK";
    /**
     * 解析token
     * @param token
     * @return json字符串
     * @throws IllegalArgumentException
     * @throws UnsupportedEncodingException
     */
    public static String parseToken(String token) {
        try {
            Claims body = Jwts.parser()
                    .setSigningKey(secret.getBytes("UTF-8"))
                    .parseClaimsJws(token)
                    .getBody();

            return body.getSubject();

        } catch (JwtException | ClassCastException | UnsupportedEncodingException e) {
            log.error("jwt token解析错误：{}", e);
            return null;
        }
    }

    /**
     * @Description 解析token内容
     *
     * @Param [token, secret]
     * @Return java.lang.String
     * @Date 4:16 下午 2020/10/21
     * @Author <a href="mailto:android_li@sina.cn">Joe</a>
     */
    public static String parseToken(String token, String secret) {
        try {
            Claims body = Jwts.parser()
                    .setSigningKey(secret.getBytes("UTF-8"))
                    .parseClaimsJws(token)
                    .getBody();

            return body.getSubject();

        } catch (JwtException | ClassCastException | UnsupportedEncodingException e) {
            log.error("jwt token解析错误：", e);
            return null;
        }
    }

    /**
     * 生成token
     * @param json
     * @return
     */
    public static String generateToken(String json) {
        try {
            return Jwts.builder()
            .setSubject(json)
            .signWith(SignatureAlgorithm.HS512, secret.getBytes("UTF-8"))
            .compact();
        } catch (UnsupportedEncodingException e) {
            log.error("jwt token解析错误：{}", e);
            return null;
        }
    }
    
    /**
     * @Description json数据加密
     *
     * @Param [json, secret]
     * @Return java.lang.String
     * @Date 4:17 下午 2020/10/21
     * @Author <a href="mailto:android_li@sina.cn">Joe</a>
     */
    public static String generateToken(String json, String secret) {
        try {
            return Jwts.builder()
            .setSubject(json)
            .signWith(SignatureAlgorithm.HS512, secret.getBytes("UTF-8"))
            .compact();
        } catch (UnsupportedEncodingException e) {
            log.error("jwt token解析错误：{}", e);
            return null;
        }
    }

    public static void main(String args[]) throws UnsupportedEncodingException {
            String json = "{name:limaoyuan}";
            String token = generateToken(json);
            System.out.println(token);
            System.out.println(parseToken(token));
    }
}